$(function () {
    getData();
})

function getData() {
    let id = localStorage.getItem("userid");
    let data = myAjax("/back/user/findById", {id: id}, "get");
    if (data != null) {
        data = data.userModel;
        // $("#username").val(data.userModel.username);
        // $("#phone").val(data.userModel.phone);
        // // $("#sex").val(data.userModel.username);
        // // $("#hobby").val(data.userModel.username);
        // $("#birthday").val(data.userModel.birthday);
        // $("#introduce").val(data.userModel.introduce);
        $("#userid").val(data.id);
        $("#username").val(data.username);
        $("#phone").val(data.phone);
        $("input[name=sex][value=" + data.sex + "]").attr("checked", true);
        $("#birthday").val(data.birthday);
        $('input:checkbox[name=hobby]').each(function () {
            let string = data.hobby;//需要将后台拿到的爱好转换为数组
            //后台传递过来的值为[羽毛球, 乒乓球, 篮球],所以需要将中括号去掉,然后用字符的方法split转换为数组
            string = string.replace("[", "").replace("]", "");
            let hobby = string.split(",");
            for (let i = 0; i < hobby.length; i++) {
                if ($(this).val() == $.trim(hobby[i])) {
                    $(this).attr('checked', true);
                    break;
                }
            }
        });
        $("#introduce").val(data.introduce);
    }
}

function save() {

    let data = {
        id: localStorage.getItem("userid"),
        username: $("#username").val(),
        password: $("#password").val(),
        phone: $("#phone").val(),
        sex: $("input[name='sex']:checked").val(),
        birthday: $("#birthday").val(),
        code: $("#code").val(),
        hobby: JSON.stringify(aihao()),
        introduce: $("#introduce").val()
    };
    $.ajax({
        url: '/back/user/edit',//和servlet里面的注解一一对应
        data: data,//传递到后台的值
        type: 'post',//和servlet里面 的do方法一致
        dataType: 'json',//后台传递到前台的值的类型 text html application json
        success: function (data) {//是后台传递到前端的值
            if (data.count == 1) {
                $("#right").load("/back/user/UserFindAll.html");
            } else {
                alert("编辑失败");
            }
        }
    })
}